package db

import (
	myDb "filestore-server/db/mysql"
	"fmt"
	"time"
)

// UserFile 用户文件表 model
type UserFile struct {
	UserName    string
	FileHash    string
	FileName    string
	FileSize    int64
	UploadAt    string
	LastUpdated string
}

// OnUserFiledUploadFinished 更新用户文件表
func OnUserFiledUploadFinished(username, filehash, filename string, filesize int64) bool {
	stmtIns, err := myDb.DBConn().Prepare(`INSERT IGNORE INTO tbl_user_file 
	(user_name, file_sha1, file_name, file_size, upload_at) VALUES (?, ?, ?, ?, ?)`)
	if err != nil {
		fmt.Printf("Failed to update user file, err: %s", err.Error())
		return false
	}
	defer stmtIns.Close()

	_, err = stmtIns.Exec(username, filehash, filename, filesize, time.Now())
	if err != nil {
		fmt.Printf("Failed to update user file, err: %s", err.Error())
		return false
	}

	return true
}

// QueryUserFileMetas 批量获取用户文件信息
func QueryUserFileMetas(username string, limit int) ([]UserFile, error) {
	stmtOut, err := myDb.DBConn().Prepare(`SELECT file_sha1, file_name, file_size, upload_at, last_update 
	FROM tbl_user_file WHERE user_name = ? LIMIT ?`)
	if err != nil {
		fmt.Printf("Failed to query user file, err: %s", err.Error())
		return nil, err
	}
	defer stmtOut.Close()

	rows, err := stmtOut.Query(username, limit)
	if err != nil {
		fmt.Printf("Failed to query user file, err: %s", err.Error())
		return nil, err
	}

	var userFiles []UserFile
	for rows.Next() {
		ufile := UserFile{}

		err := rows.Scan(&ufile.FileHash, &ufile.FileName, &ufile.FileSize, &ufile.UploadAt, &ufile.LastUpdated)
		if err != nil {
			fmt.Printf("query user file, err: %s", err.Error())
			break
		}

		userFiles = append(userFiles, ufile)
	}

	return userFiles, nil
}
